package com.hugy.test.config;

import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Scope;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.net.InetAddress;
import java.net.UnknownHostException;

@Configuration
@Slf4j
public class TransportClientConfig {

    private TransportClient transportClient;

    @Bean(name = "transportClient")
    @Scope("singleton")
    public TransportClient getClient(){
        return transportClient;
    }

    private final static String CLUSTER_NAME = "es-for-dev";
    private final static String URL = "90,91,92";

    @PostConstruct
    @Primary
    public void initClient() throws UnknownHostException{
        //设置集群名称
        Settings settings = Settings.builder()
                // 指定集群名称
                .put("cluster.name", CLUSTER_NAME)
                // 自动嗅探整个集群的状态
                .put("client.transport.sniff", true).build();
        /*
            其他配置
            client.transport.ignore_cluster_name  //设置 true ，忽略连接节点集群名验证
            client.transport.ping_timeout       //ping一个节点的响应时间 默认5秒
            client.transport.nodes_sampler_interval //sample/ping 节点的时间间隔，默认是5s
            可参考org.elasticsearch.client.transport.TransportClient类
         */
        // 是否指定底层netty的group数量
//        System.setProperty("es.set.netty.runtime.available.processors", "false");
        //创建client
        transportClient = new PreBuiltTransportClient(settings);
        transportClient.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("90"), 9300));
        transportClient.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("91"), 9300));
        transportClient.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("92"), 9300));
        // 集群
    }

    @PreDestroy
    public void destroyClient(){
        try {
            if(transportClient != null){
                transportClient.close();
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }

}
